{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3.7.9 64-bit ('ML': conda)",
   "metadata": {
    "interpreter": {
     "hash": "539eeca01c4a82e9e0248c7d96d3e95516d644c0bbc096dd3e480eeded1964cf"
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "source": [
    "<center><h1>第六章 连接</h1></center>"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "source": [
    "## 一、关系型连接\n",
    "### 1. 连接的基本概念\n",
    "\n",
    "把两张相关的表按照某一个或某一组键连接起来是一种常见操作，例如学生期末考试各个科目的成绩表按照$\\color{red}{姓名}$和$\\color{red}{班级}$连接成总的成绩表，又例如对企业员工的各类信息表按照$\\color{red}{员工ID号}$进行连接汇总。由此可以看出，在关系型连接中，$\\color{red}{键}$是十分重要的，往往用`on`参数表示。\n",
    "\n",
    "另一个重要的要素是连接的形式。在`pandas`中的关系型连接函数`merge`和`join`中提供了`how`参数来代表连接形式，分为左连接`left`、右连接`right`、内连接`inner`、外连接`outer`，它们的区别可以用如下示意图表示：\n",
    "\n",
    "<img src=\"../source/_static/ch6_1.png\" width=\"50%\">\n",
    "\n",
    "从图中可以看到，所谓左连接即以左表的键为准，如果右表中的键于左表存在，那么就添加到左表，否则则处理为缺失值，右连接类似处理。内连接只负责合并两边同时出现的键，而外连接则会在内连接的基础上包含只在左边出现以及只在右边出现的值，因此外连接又叫全连接。\n",
    "\n",
    "上面这个简单的例子中，同一个表中的键没有出现重复的情况，那么如果出现重复的键应该如何处理？只需把握一个原则，即只要两边同时出现的值，就以笛卡尔积的方式加入，如果单边出现则根据连接形式进行处理。其中，关于笛卡尔积可用如下例子说明：设左表中键`张三`出现两次，右表中的`张三`也出现两次，那么逐个进行匹配，最后产生的表必然包含`2*2`个姓名为`张三`的行。下面是一个对应例子的示意图：\n",
    "\n",
    "<img src=\"../source/_static/ch6_2.png\" width=\"60%\">\n",
    "\n",
    "显然在不同的场合应该使用不同的连接形式。其中左连接和右连接是等价的，由于它们的结果中的键是被一侧的表确定的，因此常常用于有方向性地添加到目标表。内外连接两侧的表，经常是地位类似的（左右表位置的交换不引起结果的变化），想取出键的交集或者并集，具体的操作还需要根据业务的需求来判断。\n",
    "\n",
    "### 2. 值连接\n",
    "\n",
    "在上面示意图中的例子中，两张表根据某一列的值来连接，事实上还可以通过几列值的组合进行连接，这种基于值的连接在`pandas`中可以由`merge`函数实现，例如第一张图的左连接："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Age Gender\n",
       "0  San Zhang   20    NaN\n",
       "1      Si Li   30      F"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Gender</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>30</td>\n      <td>F</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 2
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'Name':['San Zhang','Si Li'], 'Age':[20,30]})\n",
    "df2 = pd.DataFrame({'Name':['Si Li','Wu Wang'], 'Gender':['F','M']})\n",
    "df1.merge(df2, on='Name', how='left')"
   ]
  },
  {
   "source": [
    "如果两个表中想要连接的列不具备相同的列名，可以通过`left_on`和`right_on`指定："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "    df1_name  Age df2_name Gender\n",
       "0  San Zhang   20      NaN    NaN\n",
       "1      Si Li   30    Si Li      F"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>df1_name</th>\n      <th>Age</th>\n      <th>df2_name</th>\n      <th>Gender</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>30</td>\n      <td>Si Li</td>\n      <td>F</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 3
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'df1_name':['San Zhang','Si Li'], 'Age':[20,30]})\n",
    "df2 = pd.DataFrame({'df2_name':['Si Li','Wu Wang'], 'Gender':['F','M']})\n",
    "df1.merge(df2, left_on='df1_name', right_on='df2_name', how='left')"
   ]
  },
  {
   "source": [
    "如果两个表中的列出现了重复的列名，那么可以通过`suffixes`参数指定。例如合并考试成绩的时候，第一个表记录了语文成绩，第二个是数学成绩："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Grade_Chinese  Grade_Math\n",
       "0  San Zhang             70          80"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Grade_Chinese</th>\n      <th>Grade_Math</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>70</td>\n      <td>80</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 4
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'Name':['San Zhang'],'Grade':[70]})\n",
    "df2 = pd.DataFrame({'Name':['San Zhang'],'Grade':[80]})\n",
    "df1.merge(df2, on='Name', how='left', suffixes=['_Chinese','_Math'])"
   ]
  },
  {
   "source": [
    "在某些时候出现重复元素是麻烦的，例如两位同学来自不同的班级，但是姓名相同，这种时候就要指定`on`参数为多个列使得正确连接："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Age Class\n",
       "0  San Zhang   20   one\n",
       "1  San Zhang   21   two"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Class</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n      <td>one</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>San Zhang</td>\n      <td>21</td>\n      <td>two</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 5
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'Name':['San Zhang', 'San Zhang'],\n",
    "                    'Age':[20, 21],\n",
    "                    'Class':['one', 'two']})\n",
    "df2 = pd.DataFrame({'Name':['San Zhang', 'San Zhang'],\n",
    "                    'Gender':['F', 'M'],\n",
    "                    'Class':['two', 'one']})\n",
    "df1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name Gender Class\n",
       "0  San Zhang      F   two\n",
       "1  San Zhang      M   one"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Gender</th>\n      <th>Class</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>F</td>\n      <td>two</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>San Zhang</td>\n      <td>M</td>\n      <td>one</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 6
    }
   ],
   "source": [
    "df2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Age Class_x Gender Class_y\n",
       "0  San Zhang   20     one      F     two\n",
       "1  San Zhang   20     one      M     one\n",
       "2  San Zhang   21     two      F     two\n",
       "3  San Zhang   21     two      M     one"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Class_x</th>\n      <th>Gender</th>\n      <th>Class_y</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n      <td>one</td>\n      <td>F</td>\n      <td>two</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>San Zhang</td>\n      <td>20</td>\n      <td>one</td>\n      <td>M</td>\n      <td>one</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>San Zhang</td>\n      <td>21</td>\n      <td>two</td>\n      <td>F</td>\n      <td>two</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>San Zhang</td>\n      <td>21</td>\n      <td>two</td>\n      <td>M</td>\n      <td>one</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 7
    }
   ],
   "source": [
    "df1.merge(df2, on='Name', how='left') # 错误的结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Age Class Gender\n",
       "0  San Zhang   20   one      M\n",
       "1  San Zhang   21   two      F"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Class</th>\n      <th>Gender</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n      <td>one</td>\n      <td>M</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>San Zhang</td>\n      <td>21</td>\n      <td>two</td>\n      <td>F</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 8
    }
   ],
   "source": [
    "df1.merge(df2, on=['Name', 'Class'], how='left') # 正确的结果"
   ]
  },
  {
   "source": [
    "从上面的例子来看，在进行基于唯一性的连接下，如果键不是唯一的，那么结果就会产生问题。举例中的行数很少，但如果实际数据中有几十万到上百万行的进行合并时，如果想要保证唯一性，除了用`duplicated`检查是否重复外，`merge`中也提供了`validate`参数来检查连接的唯一性模式。这里共有三种模式，即一对一连接`1:1`，一对多连接`1:m`，多对一连接`m:1`连接，第一个是指左右表的键都是唯一的，后面两个分别指左表键唯一和右表键唯一。\n",
    "\n",
    "#### 【练一练】\n",
    "上面以多列为键的例子中，错误写法显然是一种多对多连接，而正确写法是一对一连接，请修改原表，使得以多列为键的正确写法能够通过`validate='1:m'`的检验，但不能通过`validate='m:1'`的检验。\n",
    "#### 【END】\n",
    "\n",
    "### 3. 索引连接\n",
    "\n",
    "所谓索引连接，就是把索引当作键，因此这和值连接本质上没有区别，`pandas`中利用`join`函数来处理索引连接，它的参数选择要少于`merge`，除了必须的`on`和`how`之外，可以对重复的列指定左右后缀`lsuffix`和`rsuffix`。其中，`on`参数指索引名，单层索引时省略参数表示按照当前索引连接。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "           Age Gender\n",
       "Name                 \n",
       "San Zhang   20    NaN\n",
       "Si Li       30      F"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Age</th>\n      <th>Gender</th>\n    </tr>\n    <tr>\n      <th>Name</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>San Zhang</th>\n      <td>20</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>Si Li</th>\n      <td>30</td>\n      <td>F</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 9
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'Age':[20,30]}, index=pd.Series(['San Zhang','Si Li'],name='Name'))\n",
    "df2 = pd.DataFrame({'Gender':['F','M']}, index=pd.Series(['Si Li','Wu Wang'],name='Name'))\n",
    "df1.join(df2, how='left')"
   ]
  },
  {
   "source": [
    "仿照第2小节的例子，写出语文和数学分数合并的`join`版本："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "           Grade_Chinese  Grade_Math\n",
       "Name                                \n",
       "San Zhang             70          80"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Grade_Chinese</th>\n      <th>Grade_Math</th>\n    </tr>\n    <tr>\n      <th>Name</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>San Zhang</th>\n      <td>70</td>\n      <td>80</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 10
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'Grade':[70]}, index=pd.Series(['San Zhang'], name='Name'))\n",
    "df2 = pd.DataFrame({'Grade':[80]}, index=pd.Series(['San Zhang'], name='Name'))\n",
    "df1.join(df2, how='left', lsuffix='_Chinese', rsuffix='_Math')"
   ]
  },
  {
   "source": [
    "如果想要进行类似于`merge`中以多列为键的操作的时候，`join`需要使用多级索引，例如在`merge`中的最后一个例子可以如下写出："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "                 Age\n",
       "Name      Class     \n",
       "San Zhang one     20\n",
       "          two     21"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Age</th>\n    </tr>\n    <tr>\n      <th>Name</th>\n      <th>Class</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">San Zhang</th>\n      <th>one</th>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>two</th>\n      <td>21</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 11
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'Age':[20,21]}, index=pd.MultiIndex.from_arrays([['San Zhang', 'San Zhang'],['one', 'two']], names=('Name','Class')))\n",
    "df2 = pd.DataFrame({'Gender':['F', 'M']}, index=pd.MultiIndex.from_arrays([['San Zhang', 'San Zhang'],['two', 'one']], names=('Name','Class')))\n",
    "df1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "                Gender\n",
       "Name      Class       \n",
       "San Zhang two        F\n",
       "          one        M"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Gender</th>\n    </tr>\n    <tr>\n      <th>Name</th>\n      <th>Class</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">San Zhang</th>\n      <th>two</th>\n      <td>F</td>\n    </tr>\n    <tr>\n      <th>one</th>\n      <td>M</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 12
    }
   ],
   "source": [
    "df2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "                 Age Gender\n",
       "Name      Class            \n",
       "San Zhang one     20      M\n",
       "          two     21      F"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Age</th>\n      <th>Gender</th>\n    </tr>\n    <tr>\n      <th>Name</th>\n      <th>Class</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">San Zhang</th>\n      <th>one</th>\n      <td>20</td>\n      <td>M</td>\n    </tr>\n    <tr>\n      <th>two</th>\n      <td>21</td>\n      <td>F</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 13
    }
   ],
   "source": [
    "df1.join(df2)"
   ]
  },
  {
   "source": [
    "## 二、方向连接\n",
    "### 1. concat\n",
    "\n",
    "前面介绍了关系型连接，其中最重要的参数是`on`和`how`，但有时候用户并不关心以哪一列为键来合并，只是希望把两个表或者多个表按照纵向或者横向拼接，为这种需求，`pandas`中提供了`concat`函数来实现。\n",
    "\n",
    "在`concat`中，最常用的有三个参数，它们是`axis, join, keys`，分别表示拼接方向，连接形式，以及在新表中指示来自于哪一张旧表的名字。这里需要特别注意，`join`和`keys`与之前提到的`join`函数和键的概念没有任何关系。\n",
    "\n",
    "在默认状态下的`axis=0`，表示纵向拼接多个表，常常用于多个样本的拼接；而`axis=1`表示横向拼接多个表，常用于多个字段或特征的拼接。\n",
    "\n",
    "例如，纵向合并各表中人的信息："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Age\n",
       "0  San Zhang   20\n",
       "1      Si Li   30\n",
       "0    Wu Wang   40"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>30</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>Wu Wang</td>\n      <td>40</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 14
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'Name':['San Zhang','Si Li'], 'Age':[20,30]})\n",
    "df2 = pd.DataFrame({'Name':['Wu Wang'], 'Age':[40]})\n",
    "pd.concat([df1, df2])"
   ]
  },
  {
   "source": [
    "横向合并各表中的字段："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Age  Grade Gender\n",
       "0  San Zhang   20     80      M\n",
       "1      Si Li   30     90      F"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Grade</th>\n      <th>Gender</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n      <td>80</td>\n      <td>M</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>30</td>\n      <td>90</td>\n      <td>F</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 15
    }
   ],
   "source": [
    "df2 = pd.DataFrame({'Grade':[80, 90]})\n",
    "df3 = pd.DataFrame({'Gender':['M', 'F']})\n",
    "pd.concat([df1, df2, df3], 1)"
   ]
  },
  {
   "source": [
    "虽然说`concat`是处理关系型合并的函数，但是它仍然是关于索引进行连接的。纵向拼接会根据列索引对其，默认状态下`join=outer`，表示保留所有的列，并将不存在的值设为缺失；`join=inner`，表示保留两个表都出现过的列。横向拼接则根据行索引对齐，`join`参数可以类似设置。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name   Age Gender\n",
       "0  San Zhang  20.0    NaN\n",
       "1      Si Li  30.0    NaN\n",
       "0    Wu Wang   NaN      M"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Gender</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>30.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>Wu Wang</td>\n      <td>NaN</td>\n      <td>M</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 16
    }
   ],
   "source": [
    "df2 = pd.DataFrame({'Name':['Wu Wang'], 'Gender':['M']})\n",
    "pd.concat([df1, df2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name   Age  Grade\n",
       "0  San Zhang  20.0    NaN\n",
       "1      Si Li  30.0   80.0\n",
       "2        NaN   NaN   90.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Grade</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>30.0</td>\n      <td>80.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>90.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 17
    }
   ],
   "source": [
    "df2 = pd.DataFrame({'Grade':[80, 90]}, index=[1, 2])\n",
    "pd.concat([df1, df2], 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "    Name  Age  Grade\n",
       "1  Si Li   30     80"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Grade</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>30</td>\n      <td>80</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 18
    }
   ],
   "source": [
    "pd.concat([df1, df2], axis=1, join='inner')"
   ]
  },
  {
   "source": [
    "因此，当确认要使用多表直接的方向合并时，尤其是横向的合并，可以先用`reset_index`方法恢复默认整数索引再进行合并，防止出现由索引的误对齐和重复索引的笛卡尔积带来的错误结果。\n",
    "\n",
    "最后，`keys`参数的使用场景在于多个表合并后，用户仍然想要知道新表中的数据来自于哪个原表，这时可以通过`keys`参数产生多级索引进行标记。例如，第一个表中都是一班的同学，而第二个表中都是二班的同学，可以使用如下方式合并："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "            Name  Age\n",
       "one 0  San Zhang   20\n",
       "    1      Si Li   21\n",
       "two 0    Wu Wang   21"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">one</th>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>two</th>\n      <th>0</th>\n      <td>Wu Wang</td>\n      <td>21</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 19
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'Name':['San Zhang','Si Li'], 'Age':[20,21]})\n",
    "df2 = pd.DataFrame({'Name':['Wu Wang'],'Age':[21]})\n",
    "pd.concat([df1, df2], keys=['one', 'two'])"
   ]
  },
  {
   "source": [
    "### 2. 序列与表的合并\n",
    "\n",
    "利用`concat`可以实现多个表之间的方向拼接，如果想要把一个序列追加到表的行末或者列末，则可以分别使用`append`和`assign`方法。\n",
    "\n",
    "在`append`中，如果原表是默认整数序列的索引，那么可以使用`ignore_index=True`对新序列对应的索引自动标号，否则必须对`Series`指定`name`属性。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Age\n",
       "0  San Zhang   20\n",
       "1      Si Li   21\n",
       "2    Wu Wang   21"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Wu Wang</td>\n      <td>21</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 20
    }
   ],
   "source": [
    "s = pd.Series(['Wu Wang', 21], index = df1.columns)\n",
    "df1.append(s, ignore_index=True)"
   ]
  },
  {
   "source": [
    "对于`assign`而言，虽然可以利用其添加新的列，但一般通过`df['new_col'] = ...`的形式就可以等价地添加新列。同时，使用`[]`修改的缺点是它会直接在原表上进行改动，而`assign`返回的是一个临时副本："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Age  Grade\n",
       "0  San Zhang   20     80\n",
       "1      Si Li   21     90"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Grade</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>21</td>\n      <td>90</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 21
    }
   ],
   "source": [
    "s = pd.Series([80, 90])\n",
    "df1.assign(Grade=s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Age  Grade\n",
       "0  San Zhang   20     80\n",
       "1      Si Li   21     90"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Age</th>\n      <th>Grade</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>20</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>21</td>\n      <td>90</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 22
    }
   ],
   "source": [
    "df1['Grade'] = s\n",
    "df1"
   ]
  },
  {
   "source": [
    "## 三、类连接操作\n",
    "\n",
    "除了上述介绍的若干连接函数之外，`pandas`中还设计了一些函数能够对两个表进行某些操作，这里把它们统称为类连接操作。\n",
    "\n",
    "### 1. 比较\n",
    "\n",
    "`compare`是在`1.1.0`后引入的新函数，它能够比较两个表或者序列的不同处并将其汇总展示："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "    Name         Class       \n",
       "    self  other   self  other\n",
       "1  Si Li  Li Si    NaN    NaN\n",
       "2    NaN    NaN  three  Three"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">Name</th>\n      <th colspan=\"2\" halign=\"left\">Class</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>self</th>\n      <th>other</th>\n      <th>self</th>\n      <th>other</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>Li Si</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>three</td>\n      <td>Three</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 23
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'Name':['San Zhang', 'Si Li', 'Wu Wang'],\n",
    "                    'Age':[20, 21 ,21],\n",
    "                    'Class':['one', 'two', 'three']})\n",
    "df2 = pd.DataFrame({'Name':['San Zhang', 'Li Si', 'Wu Wang'],\n",
    "                    'Age':[20, 21 ,21],\n",
    "                    'Class':['one', 'two', 'Three']})\n",
    "df1.compare(df2)"
   ]
  },
  {
   "source": [
    "结果中返回了不同值所在的行列，如果相同则会被填充为缺失值`NaN`，其中`other`和`self`分别指代传入的参数表和被调用的表自身。\n",
    "\n",
    "如果想要完整显示表中所有元素的比较情况，可以设置`keep_shape=True`："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "    Name         Age        Class       \n",
       "    self  other self other   self  other\n",
       "0    NaN    NaN  NaN   NaN    NaN    NaN\n",
       "1  Si Li  Li Si  NaN   NaN    NaN    NaN\n",
       "2    NaN    NaN  NaN   NaN  three  Three"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">Name</th>\n      <th colspan=\"2\" halign=\"left\">Age</th>\n      <th colspan=\"2\" halign=\"left\">Class</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>self</th>\n      <th>other</th>\n      <th>self</th>\n      <th>other</th>\n      <th>self</th>\n      <th>other</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Si Li</td>\n      <td>Li Si</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>three</td>\n      <td>Three</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 24
    }
   ],
   "source": [
    "df1.compare(df2, keep_shape=True)"
   ]
  },
  {
   "source": [
    "### 2. 组合\n",
    "\n",
    "`combine`函数能够让两张表按照一定的规则进行组合，在进行规则比较时会自动进行列索引的对齐。对于传入的函数而言，每一次操作中输入的参数是来自两个表的同名`Series`，依次传入的列是两个表列名的并集，例如下面这个例子会依次传入`A,B,C,D`四组序列，每组为左右表的两个序列。同时，进行`A`列比较的时候，`s2`指代的就是一个全空的序列，因为它在被调用的表中并不存在，并且来自第一个表的序列索引会被`reindex`成两个索引的并集。具体的过程可以通过在传入的函数中插入适当的`print`方法查看。\n",
    "\n",
    "下面的例子表示选出对应索引位置较小的元素："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "    A    B    C   D\n",
       "0 NaN  NaN  NaN NaN\n",
       "1 NaN  4.0  6.0 NaN\n",
       "2 NaN  NaN  NaN NaN"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n      <th>C</th>\n      <th>D</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>NaN</td>\n      <td>4.0</td>\n      <td>6.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 25
    }
   ],
   "source": [
    "def choose_min(s1, s2):\n",
    "    s2 = s2.reindex_like(s1)\n",
    "    res = s1.where(s1<s2, s2)\n",
    "    res = res.mask(s1.isna()) # isna表示是否为缺失值，返回布尔序列\n",
    "    return res\n",
    "df1 = pd.DataFrame({'A':[1,2], 'B':[3,4], 'C':[5,6]})\n",
    "df2 = pd.DataFrame({'B':[5,6], 'C':[7,8], 'D':[9,10]}, index=[1,2])\n",
    "df1.combine(df2, choose_min)"
   ]
  },
  {
   "source": [
    "#### 【练一练】\n",
    "请在上述代码的基础上修改，保留`df2`中4个未被`df1`替换的相应位置原始值。\n",
    "#### 【END】\n",
    "此外，设置`overtwrite`参数为`False`可以保留$\\color{red}{被调用表}$中未出现在传入的参数表中的列，而不会设置未缺失值："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "     A    B    C   D\n",
       "0  1.0  NaN  NaN NaN\n",
       "1  2.0  4.0  6.0 NaN\n",
       "2  NaN  NaN  NaN NaN"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n      <th>C</th>\n      <th>D</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2.0</td>\n      <td>4.0</td>\n      <td>6.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n      <td>NaN</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 26
    }
   ],
   "source": [
    "df1.combine(df2, choose_min, overwrite=False)"
   ]
  },
  {
   "source": [
    "#### 【练一练】\n",
    "除了`combine`之外，`pandas`中还有一个`combine_first`方法，其功能是在对两张表组合时，若第二张表中的值在第一张表中对应索引位置的值不是缺失状态，那么就使用第一张表的值填充。下面给出一个例子，请用`combine`函数完成相同的功能。\n",
    "#### 【END】"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "     A    B\n",
       "0  1.0  3.0\n",
       "1  2.0  7.0\n",
       "2  6.0  8.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1.0</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2.0</td>\n      <td>7.0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>6.0</td>\n      <td>8.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 27
    }
   ],
   "source": [
    "df1 = pd.DataFrame({'A':[1,2], 'B':[3,np.nan]})\n",
    "df2 = pd.DataFrame({'A':[5,6], 'B':[7,8]}, index=[1,2])\n",
    "df1.combine_first(df2)"
   ]
  },
  {
   "source": [
    "## 四、练习\n",
    "### Ex1：美国疫情数据集\n",
    "\n",
    "现有美国4月12日至11月16日的疫情报表（在`/data/us_report`文件夹下），请将`New York`的`Confirmed, Deaths, Recovered, Active`合并为一张表，索引为按如下方法生成的日期字符串序列："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "['04-12-2020', '04-13-2020', '04-14-2020', '04-15-2020', '04-16-2020']"
      ]
     },
     "metadata": {},
     "execution_count": 28
    }
   ],
   "source": [
    "date = pd.date_range('20200412', '20201116').to_series()\n",
    "date = date.dt.month.astype('string').str.zfill(2) +'-'+ date.dt.day.astype('string').str.zfill(2) +'-'+ '2020'\n",
    "date = date.tolist()\n",
    "date[:5]"
   ]
  },
  {
   "source": [
    "### Ex2：实现join函数\n",
    "\n",
    "请实现带有`how`参数的`join`函数\n",
    "\n",
    "* 假设连接的两表无公共列\n",
    "* 调用方式为 `join(df1, df2, how=\"left\")`\n",
    "* 给出测试样例"
   ],
   "cell_type": "markdown",
   "metadata": {}
  }
 ]
}